﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

using ET;

namespace Marx
{
    public static class HotfixCodeHelper
    {
        public static Assembly HotfixEntry;

        public static void LoadCode(string hotfixPath, string entryAssembly)
        {
            if (string.IsNullOrEmpty(hotfixPath))
            {
                throw new Exception("请配置热更代码资产路径，如果不需要热更代码，请调用LoadCodeDirectly");
            }

            var config = Host.Instance.GetConfiguration();
            var prefab = ResHelper.LoadPrefab(hotfixPath);
            var hotfix = prefab.GetComponent<HotfixCodeBehaviour>();
            foreach (var codes in hotfix.Codes)
            {
                var ass = Assembly.Load(codes.bytes);
                config.UseDLL(ass);

                if(ass.GetName().Name == entryAssembly)
                {
                    HotfixEntry = ass;
                }
            }
            Game.EventSystem.Load();
        }

        public static void LoadCodeDirectly(string[] assemblies, string entryAssembly)
        {
            var config = Host.Instance.GetConfiguration();
            var all = AppDomain.CurrentDomain.GetAssemblies();
            foreach(var item in all)
            {
                var name = item.GetName().Name;
                if (assemblies.Contains(name))
                {
                    config.UseDLL(item);
                    if(name == entryAssembly)
                    {
                        HotfixEntry = item;
                    }
                }
            }
            Game.EventSystem.Load();
        }
    }
}
